package rest

import (
	"../dog"
	"net/http"
	"strconv"
)

type DogInDogsModel struct {
	url_model

	Id   int
	Name string
}

type DogsModel struct {
	url_model

	Dogs     []DogInDogsModel
}

type DogsController struct {
	dogkeeper *dog.DogKeeper
}

func (this *DogsController) GetSourceName() string {
	return "/API/Dogs"
}

func (this *DogsController) IsRoot() bool {
	return true
}

func (this *DogsController) Get(req interface{}) interface{} {
	if this.dogkeeper == nil {
		return Error(this, "not found dogkeeper")
	}

	dogs := this.dogkeeper.GetAllDog()
	var dog_models []DogInDogsModel

	for i := 0; i < len(dogs); i++ {
		item_dog := dogs[i]
		dog_models = append(dog_models, DogInDogsModel{
			url_model: url_model{
				Url: GetDogItemUrl(item_dog.GetDogId()),
			},
			Id:   item_dog.GetDogId(),
			Name: item_dog.GetDogName(),
		})
	}

	return &DogsModel{
		url_model: url_model{
			Url: this.GetSourceName(),
		},
		Dogs: dog_models,
	}
}

func (this *DogsController) Put(r interface{}) interface{} {
	request, success := r.(*http.Request)
	if !success {
		return Error(this, "not found request")
	}

	// 需要创建新狗的参数
	err := request.ParseForm()
	if err != nil {
		return Error(this, err.Error());
	}

	name2value := make(map[string]string)

	ref_name := [...]string{"DogType", "Name", "HungerCycle", "LastWord", "LastWordCMD"}
	for i := range ref_name {
		item_value := request.FormValue(ref_name[i])
		if item_value == "" {
			return Error(this, "Missing necessary fields "+ref_name[i])
		}

		name2value[ref_name[i]] = item_value
	}

	dog_instance := dog.GetDefaultDogFactory().CreateDog(name2value["DogType"])
	if dog_instance == nil {
		return Error(this, "create dog error by "+name2value["DogType"])
	}

	dog_instance.SetDogName(name2value["Name"])

	//i_hc, err := strconv.Atoi(name2value["HungerCycle"])
	i_hc, err := strconv.ParseInt(name2value["HungerCycle"], 10, 64)
	if err != nil {
		return Error(this, "convert HungerCycle error "+err.Error())
	}
	dog_instance.SetHungerCycle(i_hc)

	lw := dog.GetDefaultLastWordFactory().CreateLastWord(name2value["LastWord"], name2value["LastWordCMD"])
	if lw == nil {
		return Error(this, "create last word error "+name2value["LastWord"]+name2value["LastWordCMD"])
	}

	dog_instance.SetLastWord(lw)
	dog_instance.Feed()

	this.dogkeeper.FosterageADog(dog_instance)

	return DogModel{
		url_model: url_model{
			Url: GetDogItemUrl(dog_instance.GetDogId()),
		},
		Name:        dog_instance.GetDogName(),
		Id:          dog_instance.GetDogId(),
		HungerCycle: dog_instance.GetHungerCycle(),
		LifeCycle:   dog_instance.GetLifeCycle(),
	}
}
